package com.project.server.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.server.entity.Consultation;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.Map;

@Mapper
public interface ConsultationMapper extends BaseMapper<Consultation> {

    @Select("SELECT c.*, " +
            "p.real_name as patientName, p.gender, p.age, " +
            "d.real_name as doctorName, d.title as doctorTitle " +
            "FROM consultation c " +
            "LEFT JOIN user p ON c.patient_id = p.id " +
            "LEFT JOIN user d ON c.doctor_id = d.id " +
            "WHERE c.doctor_id = #{doctorId} " +
            "${status != null ? 'AND c.status = #{status}' : ''} " +
            "ORDER BY c.create_time DESC")
    IPage<Map<String, Object>> selectConsultationList(Page<Object> page, Integer status, Long doctorId);

    @Select("SELECT c.*, " +
            "p.real_name as patientName, p.gender, p.age, p.phone, " +
            "p.height, p.weight, p.blood_type as bloodType, p.allergies, " +
            "d.real_name as doctorName, d.title as doctorTitle, " +
            "d.avatar as doctorAvatar, p.avatar as patientAvatar " +
            "FROM consultation c " +
            "LEFT JOIN user p ON c.patient_id = p.id " +
            "LEFT JOIN user d ON c.doctor_id = d.id " +
            "WHERE c.id = #{id}")
    Map<String, Object> selectConsultationDetail(Long id);

    @Select("SELECT " +
            "ROUND(AVG(r.rating), 1) as avgRating, " +
            "COUNT(DISTINCT c.patient_id) as patientCount, " +
            "SUM(CASE WHEN repeat_count > 1 THEN 1 ELSE 0 END) as repeatCount " +
            "FROM doctor_consultation c " +
            "LEFT JOIN consultation_rating r ON c.id = r.consultation_id " +
            "LEFT JOIN (SELECT patient_id, COUNT(*) as repeat_count " +
            "          FROM doctor_consultation " +
            "          WHERE doctor_id = #{doctorId} " +
            "          GROUP BY patient_id) t ON c.patient_id = t.patient_id " +
            "WHERE c.doctor_id = #{doctorId}")
    Map<String, Object> selectRatingStats(Long doctorId);


    void updateStatus(Long id, Integer status, Long doctorId);


    void endConsultation(Long id, String diagnosis, Long doctorId);


}
